package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.Exception.LeaseException;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
        /*创建随机的一个验证码图像（二进制）*/
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        /*图像对应的值，并将值转化为小写（实现不区分大小写）*/
        String code = specCaptcha.text().toLowerCase();
        /*为图像标识唯一id,方便存储到redis中*/
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        /*存到redis中，并设置超时时间*/
        stringRedisTemplate.opsForValue()
                .set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        /*.toBase64()返回的值，前端可以直接使用赋值给img标签中src属性，自动显示一个验证码*/
        String image = specCaptcha.toBase64();
        return new CaptchaVo(image, key);
    }

    @Override
    public String loginCheck(LoginVo loginVo) {
        /*1、判断验证码是否为空*/
        if (loginVo.getCaptchaCode()==null) throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        /*2、验证码是否过期*/
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code==null) throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        /*3、验证码是否正确*/
        if (!loginVo.getCaptchaCode().toLowerCase().equals(code))
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        /*4、用户是否存在*/
        SystemUser user = systemUserMapper.getByUserName(loginVo.getUsername());
        if (user == null) throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        /*5、该账号是否被禁用*/
        if (user.getStatus() == BaseStatus.DISABLE)
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        /*6、密码是否正确*/
        if (!user.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword())))
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);

        return JwtUtil.generateJwt(user.getUsername(), user.getId());
    }
}
